package project.main;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import project.dbaccesslayer.MySQLAccessLayer;

public class DownloadAndDeleteHtml {

	public static void main(String[] args) throws IOException, SQLException {
		if (args.length != 1) {
			System.out.println("Usage: DownloadAndDeleteHtml <limit>");
			return;
		}
		int limit = Integer.parseInt(args[0]);

		Connection conn = MySQLAccessLayer.openConnectionToMySql();

		PreparedStatement s = conn.prepareStatement("SELECT Question_Id, html"
				+ " FROM SO_Questions_Raw_html" + " WHERE	Question_ID IN ("
				+ " 	SELECT Question_ID " + " 	FROM SO_Questions"
				+ " ) AND LENGTH(html) > 0" + " LIMIT " + limit);

		ResultSet r = s.executeQuery();

		List<Long> toDelete = new ArrayList<Long>();

		while (r.next()) {
			long qID = r.getLong("Question_Id");
			System.out.println("Got " + qID);
			String html = r.getString("html");
			Files.write(Paths.get("data", qID + ""), html.getBytes());
			toDelete.add(qID);
		}

		s = conn.prepareStatement("UPDATE SO_Questions_Raw_html"
				+ " SET html=''"
				+ " WHERE	Question_ID IN ("
				+ toDelete.toString().replaceAll("\\[", "")
						.replaceAll("\\]", "") + " )");

		System.out.println(s);
		int count = s.executeUpdate();

		System.out.println(count);

		System.out.println("Done.");

		conn.close();
	}

}
